package com.example.auction.activity;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.*;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.auction.R;
import com.example.auction.bean.Item;
import com.example.auction.sqlite.Sqlite;
import com.example.auction.util.MyUtil;
import com.example.auction.util.UserDialog;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddItemActivity extends AppCompatActivity {

    private TextView tvCencel, tvEndTime;
    private Button btnPublish;
    private ImageView ivItemImg;
    private EditText etItemName, etItemDes, etInitPrice, etMarkupPrice;
    private AppCompatSpinner spItemKind;

    private SimpleDateFormat sdf;
    private Date nowTime;
    private String end_time, add_time;

    private Integer user_id = 0;
    private String[] kinds;
    private String selectedKindName;

    Sqlite sqlite = new Sqlite(AddItemActivity.this);
    private byte[] image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_item);

        findViewId();
        initData();
    }

    private void initData() {
        //获取用户id
        user_id = getIntent().getExtras().getInt("user_id");
        //从res中获取分类的子项
        kinds = getResources().getStringArray(R.array.item_kind);
        //结束时间默认为当前时间
        sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        nowTime = new Date(System.currentTimeMillis());
        end_time = sdf.format(nowTime);
        tvEndTime.setText(end_time);

        tvCencel.setOnClickListener(new topBtnClick());
        btnPublish.setOnClickListener(new topBtnClick());
        //从相册选择图片
        ivItemImg.setOnClickListener(new photoByAlbum());
        //类别选择下拉框
        spItemKind.setOnItemSelectedListener(new spinnerItemSelect());
        //时间选择框
        tvEndTime.setOnClickListener(new chooseEndTime());
    }

    private void findViewId() {
        tvCencel = (TextView) findViewById(R.id.tv_cencel);
        btnPublish = (Button) findViewById(R.id.btn_publish);
        ivItemImg = (ImageView) findViewById(R.id.iv_item_img);
        etItemName = (EditText) findViewById(R.id.et_item_name);
        etItemDes = (EditText) findViewById(R.id.et_item_des);
        spItemKind = (AppCompatSpinner) findViewById(R.id.sp_item_kind);
        etInitPrice = (EditText) findViewById(R.id.et_init_price);
        etMarkupPrice = (EditText) findViewById(R.id.et_markup_price);
        tvEndTime = (TextView) findViewById(R.id.tv_end_time);
//        date_picker = findViewById(R.id.date_picker);
    }

    //顶部取消和发布功能
    private class topBtnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                case R.id.tv_cencel:
                    AddItemActivity.this.finish();
                    break;
                case R.id.btn_publish:
                    UserDialog publishDialog = new UserDialog(AddItemActivity.this, new UserDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            publish();
                            dialog.dismiss();
                        }
                    });
                    //不要忘了show
                    publishDialog.setTitle("确认发布").show();
                    publishDialog.setContent("审核通过后，发布内容不可再修改！").show();
                    break;
            }
        }
    }

    //发布方法
    private void publish() {
        // 获取当前时间
//        nowTime = new Date(System.currentTimeMillis());
        add_time = MyUtil.getNowDateString();

        if (checkInfo()) {
            //提交成功向item表中插入数据
            // 初始时让最高价格为起拍价格
            Item item = new Item();
            setItem(item);
            if (sqlite.insertItem(item) > 0) {
                //拍卖品信息插入成功
                Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(AddItemActivity.this, UserUIBaseActivity.class);
                intent.putExtra("user_id", user_id);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                AddItemActivity.this.finish();
            } else {
                //拍卖品信息插入失败
                Toast.makeText(getApplicationContext(), "发布失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void setItem(Item item) {
        item.setImage(image);
        item.setItemName(etItemName.getText().toString().trim());
        item.setItemDesc(etItemDes.getText().toString().trim());
        item.setAddtime(add_time.trim());
        item.setEndtime(end_time.trim());
        item.setInitPrice(etInitPrice.getText().toString().trim());
        //发布时的最高价等于发布价
        item.setMaxPrice(etInitPrice.getText().toString().trim());
        //加价幅度
        item.setMarkupPrice(etMarkupPrice.getText().toString().trim());
        item.setOwnerId(user_id);
        item.setKind(selectedKindName);
        item.setWinnerId(0);
        item.setItemRemark(null);
        item.setOwnerVisible(1);
        item.setWinnerVisible(1);
        item.setState("审核中".trim());
    }

    private boolean checkInfo() {
        boolean flag = true;
        if (etItemName.getText().toString().trim().equals("")
                || etItemDes.getText().toString().trim().equals("")
                || etInitPrice.getText().toString().trim().equals("")
                || etMarkupPrice.getText().toString().trim().equals("")) {
            Toast.makeText(getApplicationContext(),
                    "请您将信息补充完整", Toast.LENGTH_SHORT).show();
            flag = false;
        }
        if (!(end_time.equals(add_time))) {
            //MyUtil.compareDate返回boolean日期1是否大于等于日期2加上天数day
            if (!MyUtil.compareDate(end_time, add_time, 1)) {
                Toast.makeText(getApplicationContext(),
                        "你的结束日期不足24小时", Toast.LENGTH_SHORT).show();
                flag = false;
            }
            if (MyUtil.compareDate(end_time, add_time, 30)) {
                Toast.makeText(getApplicationContext(),
                        "结束日期超过30天！", Toast.LENGTH_SHORT).show();
                flag = false;
            }
        } else {
            Toast.makeText(AddItemActivity.this,
                    "你还没有选择结束时间！", Toast.LENGTH_SHORT).show();
            flag = false;
        }
        if (image == null) {
            Toast.makeText(AddItemActivity.this,
                    "上传一张照片吧~", Toast.LENGTH_SHORT).show();
            flag = false;
        }
        if (!etMarkupPrice.getText().toString().trim().equals("")) {
            if (Integer.valueOf(etMarkupPrice.getText().toString().trim()) > 50) {
                Toast.makeText(AddItemActivity.this,
                        "加价幅度不能大于50元", Toast.LENGTH_SHORT).show();
                flag = false;
            }
            if (Integer.valueOf(etMarkupPrice.getText().toString().trim()) < 1) {
                Toast.makeText(AddItemActivity.this,
                        "加价幅度不能小于1哦~", Toast.LENGTH_SHORT).show();
                flag = false;
            }
        }
        if (!etInitPrice.getText().toString().trim().equals("")) {
            if (Integer.valueOf(etInitPrice.getText().toString().trim()) > 9999) {
                Toast.makeText(AddItemActivity.this,
                        "给一个物美价廉的价格吧~", Toast.LENGTH_SHORT).show();
                flag = false;
            }
            if (Integer.valueOf(etInitPrice.getText().toString().trim()) < 1) {
                Toast.makeText(AddItemActivity.this,
                        "物品价格至少为1哦~", Toast.LENGTH_SHORT).show();
                flag = false;
            }
        }

        return flag;
    }

    //下拉框选择分类
    private class spinnerItemSelect implements AdapterView.OnItemSelectedListener {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            //获取选择而的城市名字
            selectedKindName = kinds[position];
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    }

    //选择结束时间
    private class chooseEndTime implements View.OnClickListener {
        //创建日期选择框默认时间
        Date dt = new Date();
        //Date年份要等于现实年份要加1900
        int mYear = dt.getYear() + 1900;
        int mMonth = dt.getMonth();
        int mDay = dt.getDate() + 1;
        int mHour = dt.getHours();
        int mMin = dt.getMinutes();

        @Override
        public void onClick(View v) {
            //日期选择框对象
            //参数：上下文、new时间列表对象、初始年、初始月、初始日
            new DatePickerDialog(AddItemActivity.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    //月份是从0开始算的，记得加1
                    String chooseDate = year + "." + (month + 1) + "." + dayOfMonth;
                    //时间选择方法
                    new TimePickerDialog(AddItemActivity.this, new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm");
                            Date date = new Date();
                            //年份保存到Date里面要-1900
                            date.setYear(year - 1900);
                            date.setMonth((month));
                            date.setDate(dayOfMonth);
                            date.setHours(hourOfDay);
                            date.setMinutes(minute);
                            end_time = sdf.format(date);
                            tvEndTime.setText(end_time);
                        }
                        //设置日期选择框默认时间
                        // 不要忘了TimePickerDialog()的.show()
                    }, mHour, mMin, true).show();
                }
                //设置日期选择框默认时间
                // 不要忘了DatePickerDialog()的.show()
            }, mYear, mMonth, mDay).show();
        }
    }

    //从相册选择图片
    private class photoByAlbum implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (ContextCompat.checkSelfPermission(AddItemActivity.this,
                    //没有获得权限
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //重新申请权限
                ActivityCompat.requestPermissions(AddItemActivity.this, new
                        String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            } else {
                //已有权限
                //打开系统相册
//                Intent intent = new Intent(Intent.ACTION_PICK,
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);
            }
        }
    }

    //返回从相册选择的图片
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
            String imagePath = cursor.getString(columnIndex);
            try {
                showImage(imagePath);
//                Toast.makeText(this, "showImage", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
            }
            cursor.close();
        }

//        if (requestCode == 1) {
//            //从相册返回的数据
//            if (data != null) {
//                //得到图片的全路径
//                Uri uri = data.getData();
//                ivItemImg.setImageURI(uri);
//                //把图片先转化成bitmap格式
//                BitmapDrawable drawable = (BitmapDrawable) ivItemImg.getDrawable();
//                Bitmap bitmap = drawable.getBitmap();
//                //二进制数组输出流
//                ByteArrayOutputStream byStream = new ByteArrayOutputStream();
//                //将图片压缩成质量为100的PNG格式图片
//                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byStream);
//                //把输出流转换为二进制数组
//                byteArray = byStream.toByteArray();
//            }
//        }
    }

    //加载图片
    private void showImage(String imaePath) throws IOException {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);

        //转成byte类型存进数据库
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        //转换成byte才能存进数据库
//        image = baos.toByteArray();
//        //替换原本图片
//        ivItemImg.setImageBitmap(bm);

        //创建一个字节数组输出流,流的大小为size
        int size = bm.getWidth() * bm.getHeight() * 4;
        ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
        //设置位图的压缩格式，质量为100%，并放入字节数组输出流中
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        //将字节数组输出流转化为字节数组byte[]
        image = baos.toByteArray();
        ivItemImg.setImageBitmap(bm);
        baos.close();

    }
}